package com.tanhua.dubbo.api;

import cn.hutool.core.util.ObjectUtil;
import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/1
 */
@DubboService
public class VisitorsApiImpl implements VisitorsApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存访客数据(同一个用户一天内只能保存一次)
     * @param visitors
     */
    @Override
    public void saveVisitors(Visitors visitors) {
        Criteria criteria = Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate());
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, Visitors.class);
        if (!exists) {
            mongoTemplate.save(visitors);
        }
    }

    @Override
    public List<Visitors> getList(Long userId, Long date) {
        Criteria criteria = Criteria.where("userId").is(userId);
        if (ObjectUtil.isNotEmpty(date)) {
            criteria.and("date").gt(date);
        }
        Query query = Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date")));
        return mongoTemplate.find(query, Visitors.class);
    }

    @Override
    public List<Visitors> getVisitors(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Long skip = Long.valueOf((page - 1) * pagesize);
        Query query = Query.query(criteria)
                .skip(skip).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("date")));
        return mongoTemplate.find(query, Visitors.class);
    }
}
